import {login, getUserInfo, logout} from '@/api/auth/auth'
import { getToken, setToken ,removeToken} from '@/utils/token'
import da from "element-ui/src/locale/lang/da";

//定义全局数据
const state = {
    token: getToken(), // token
    user: '', // 用户对象
}

//state必须通过mutations改变，类似java中的 set
const mutations = {
    SET_TOKEN_STATE: (state, token) => {
        state.token = token
    },
    SET_USER_STATE: (state, user) => {
        state.user = user
    }
}

//mutations不能接受异步请求，后台发过来的异步请求放在actions中处理
const actions = {
    // 用户登录
    login({ commit }, userInfo) {
        const { name, pass, rememberMe } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: name.trim(), password: pass, rememberMe: rememberMe })
                .then(response => {
                const { data } = response
                //放在vuex的store下
                commit('SET_TOKEN_STATE', data.token)
                //放在cookie下
                setToken(data.token)
                resolve(response)
            })
                //指定发生错误时的回调函数。
                .catch(error => {
                reject(error)
            })
        })
    },
    // 获取用户信息
    getInfo({ commit }) {
        return new Promise((resolve, reject) => {
            getUserInfo()
                .then(response => {
                    const { data } = response
                    console.log(data)
                    if (!data){
                        commit('SET_TOKEN_STATE', '')
                        commit('SET_USER_STATE', '')
                        removeToken()
                        resolve()
                        reject('Verification failed,please Login again')
                    }
                    //放在vuex的store下
                    commit('SET_USER_STATE', data)
                    resolve(data)
                })
                //指定发生错误时的回调函数。
                .catch(error => {
                    reject(error)
                })
        })
    },
    // 用户退出
    logout({ commit }) {
        return new Promise((resolve, reject) => {
            logout(state.token)
                .then(response => {
                    console.log(response)
                    //放在vuex的store下
                    commit('SET_TOKEN_STATE', "")
                    commit('SET_USER_STATE', "")
                    removeToken()
                    resolve()
                })
                //指定发生错误时的回调函数。
                .catch(error => {
                    reject(error)
                })
        })
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}